package com.hakim.wfb.schedule.config;

import com.hakim.wfb.schedule.dao.scheduleDao;
import com.hkfs.fundamental.spring.utils.SpringContextUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class ScheduleInfoAction {

    private Logger logger = LoggerFactory.getLogger(ScheduleInfoAction.class);

    private Scheduler scheduler;

    public void reScheduleJob() throws SchedulerException {
        scheduler = (Scheduler) SpringContextUtils.getBean("schedulerFactory");
        List<String> jobs = scheduleDao.getJobCodesFromDB(null);

        if (jobs != null && !jobs.isEmpty()) {
            for (String job : jobs) {
                TriggerKey triggerKey = new TriggerKey(job + "CronTrigger", Scheduler.DEFAULT_GROUP);
                CronTriggerImpl trigger = (CronTriggerImpl) scheduler.getTrigger(triggerKey);

                String dbCronExpression = getCronExpressionFromDB(job);
//                String dbCronExpression = scheduleDao.getCronByCode(job);
                String originConExpression;
                if (StringUtils.isNotBlank(dbCronExpression)) {
                    if (trigger != null) {
                        originConExpression = trigger.getCronExpression();
                        if (!dbCronExpression.equalsIgnoreCase(originConExpression)) {
                            try {
                                trigger.setCronExpression(dbCronExpression);
                                scheduler.rescheduleJob(triggerKey, trigger);
                                logger.info("jobCode:{}, dbCron:{}, originCron:{}", job, dbCronExpression, originConExpression);
                            } catch (Exception e) {
                                logger.error("jobCode:{}, dbCron:{}, originCron:{}, refresh Cron Error:{}", job,
                                        dbCronExpression, originConExpression, e);
                            }
                        }
                    } else {
                        trigger = (CronTriggerImpl) SpringContextUtils
                                .getBean(job + "CronTrigger");
                        if (trigger != null) {
                            scheduler.scheduleJob(trigger);
                            logger.info("scheduleJob:{}", job);
                        }
                    }
                } else {
                    if (trigger != null) {
                        scheduler.unscheduleJob(triggerKey);
                        logger.info("unscheduleJob:{}", job);
                    }
                }
            }
        }
    }

    private String getCronExpressionFromDB(String jobName) {
        return scheduleDao.getCronByCode(jobName);
    }
}
